package services;

import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import helpers.StringHelper;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import debug.IpTrackDebug;


import models.IpTrack;

public class UpdateIp {
	public UpdateIp(String ip, String domainName) {
		//Check ip exists
		ip = ip.replaceAll("(#[0-9]+)*", "");
		
		try {
			ObjectifyService.register(IpTrack.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		Objectify ofy = ObjectifyService.begin();
		IpTrack ipTrack = new IpTrack();
		try {
			ipTrack = ofy.get(new Key<IpTrack>(IpTrack.class, ip));
		} catch (Exception e) {
			ipTrack = null;
		}
		//IpTrack ipTrack = ofy.query(IpTrack.class).filter("ip", ip).get();
		
		if (ipTrack != null) {
			List<String> domains = ipTrack.getDomain();
			if (!domains.contains(domainName)) {
				domains.add(domainName);
			}
			ipTrack.setDomain(domains);
			ipTrack = getTrackIp(ipTrack);
		} else {
			ipTrack = new IpTrack();
			ipTrack.setIp(ip);
			ipTrack.setDomain(Arrays.asList(domainName));
			ipTrack = getTrackIp(ipTrack);
		}
		ipTrack.setDate(new Date());
		
		ofy.put(ipTrack);
		System.out.println("Update ip success: " + ip);
	}
	
	public static IpTrack getTrackIp(IpTrack ipTrack) {
		String url = "http://whatismyipaddress.com/ip/" + ipTrack.getIp();
		try {
			Document doc = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1").get();
			ipTrack.setJsp(doc.select("div[id=section_content]").select("table").get(0).select("td").get(1).text());
			ipTrack.setOrganization(doc.select("div[id=section_content]").select("table").get(0).select("td").get(2).text());
			ipTrack.setProxy(doc.select("div[id=section_content]").select("table").get(0).select("td").get(3).text());
			ipTrack.setType(doc.select("div[id=section_content]").select("table").get(0).select("td").get(4).text());
			ipTrack.setAssignment(doc.select("div[id=section_content]").select("table").get(0).select("td").get(5).text());
			ipTrack.setCountry(doc.select("div[id=section_content]").select("table").get(1).select("td").get(0).text());
			ipTrack.setState(doc.select("div[id=section_content]").select("table").get(1).select("td").get(1).text());
			ipTrack.setCity(doc.select("div[id=section_content]").select("table").get(1).select("td").get(2).text());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ipTrack;
	}
}
